package eu.jba.denshijisho;

import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import eu.jba.denshijisho.adapter.ConfigurationAdapter;
import eu.jba.denshijisho.dao.ConfigurationDao;
import eu.jba.denshijisho.entity.Configuration;
import eu.jba.denshijisho.exceptionhandler.ExceptionHandler;
import eu.jba.denshijisho.listeners.ListenersHelper;
import eu.jba.denshijisho.util.Constants;

public class SettingsActivity extends AbstractDenshiActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Thread.setDefaultUncaughtExceptionHandler( new ExceptionHandler( this ));
		setContentView( R.layout.activity_settings );
		final ConfigurationDao configurationDao = new ConfigurationDao(this);
		configurationDao.open();
		final ListView lv = (ListView)findViewById(R.id.configuration_list_view_main);
		final ConfigurationAdapter arrayList = new ConfigurationAdapter(
			this, R.layout.listview_item_row2, configurationDao.getAll()
		);
		lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		lv.setOnItemClickListener( ListenersHelper.getListViewItemListener() );
		lv.setAdapter( arrayList );
		registerForContextMenu(lv);
		
		configurationDao.close();
	}

	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		getMenuInflater().inflate(R.menu.context_action_settings_menu, menu);
	}

	public boolean onContextItemSelected(MenuItem item) {
		final AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		final ListView lv = (ListView) findViewById(R.id.configuration_list_view_main);
		final ConfigurationAdapter configurationAdapter = (ConfigurationAdapter) lv.getAdapter();
		final Configuration configuration = configurationAdapter.getItem(menuInfo.position);
		
		if( item.getItemId() == R.id.edit){
			Intent edit = new Intent( this, EditConfigValueActivity.class );
			edit.putExtra(Constants.CONFIGURATION, configuration);
			startActivityForResult( edit, 1 );
		}
		return super.onContextItemSelected(item);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			updateListView();
		}
	}

	private void updateListView() {
		final ListView lv = (ListView) findViewById(R.id.configuration_list_view_main);
		final ConfigurationDao configurationDao = new ConfigurationDao(this);
		configurationDao.open();
		final ConfigurationAdapter arrayAdapter = new ConfigurationAdapter(this,
				R.layout.listview_item_row2, configurationDao.getAll());
		lv.setAdapter(arrayAdapter);
		configurationDao.close();
	}
}
